package com.winapi.project.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.winapi.project.constant.OrderStatus;
import com.winapi.project.mapper.AlipayInfoMapper;
import com.winapi.project.model.entity.AlipayInfo;
import com.winapi.project.service.AlipayInfoService;
import com.winapi.project.service.OrderService;
import com.winapi.project.service.UserInterfaceInfoService;
import com.winapi.winapicommon.model.entity.Orders;
import com.winapi.winapicommon.model.entity.UserInterfaceInfo;
import com.winapi.winapicommon.model.enums.AliPayTradeState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 *
 */
@Service
@Slf4j
public class AlipayInfoServiceImpl extends ServiceImpl<AlipayInfoMapper, AlipayInfo>
    implements AlipayInfoService {
    @Resource
    private AlipayClient alipayClient;
    @Resource
    private OrderService orderService;
    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    @Override
    public String queryOrder(String traceNo) {
        try{
        String outTradeNo = traceNo;
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setOutTradeNo(outTradeNo);
        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        log.info("查询结果"+response.getBody());
        if(response.isSuccess()){
            System.out.println("调用成功");
            return response.getBody();
        } else {
            System.out.println("调用失败");
            return null;
        }

      } catch (AlipayApiException e) {
        e.printStackTrace();
        throw new RuntimeException("查单接口的调用失败");
    }

    }

    /**
     * 根据订单号调用支付宝查单接口，核实订单状态
     * 如果订单未创建，则更新商户端订单状态
     * 如果订单未支付，则调用关单接口关闭订单，并更新商户端订单状态
     * 如果订单已支付，则更新商户端订单状态，并记录支付日志
     * @param orderNumber
     */
    @Override
    public void checkOrderStatus(String orderNumber) {
        log.warn("根据订单号核实订单状态 ===> {}", orderNumber);

        String result = this.queryOrder(orderNumber);

        //订单未创建
        if(result == null){
            log.warn("核实订单未创建 ===> {}", orderNumber);
            //更新本地订单状态
            orderService.updateStatusByOrderNo(orderNumber, OrderStatus.EXPIRE);
        }

        //解析查单响应结果
        Gson gson = new Gson();
        HashMap<String, LinkedTreeMap> resultMap = gson.fromJson(result, HashMap.class);
        LinkedTreeMap alipayTradeQueryResponse = resultMap.get("alipay_trade_query_response");

        String tradeStatus = (String)alipayTradeQueryResponse.get("trade_status");
        if(AliPayTradeState.NOTPAY.getType().equals(tradeStatus)){
            log.warn("核实订单未支付 ===> {}", orderNumber);

            //如果订单未支付，则调用关单接口关闭订单
            this.closeOrder(orderNumber);

            // 并更新商户端订单状态
            orderService.updateStatusByOrderNo(orderNumber, OrderStatus.EXPIRE);
        }

        if(AliPayTradeState.SUCCESS.getType().equals(tradeStatus)){
            log.warn("核实订单已支付 ===> {}", orderNumber);

            //如果订单已支付，则更新商户端订单状态
            orderService.updateStatusByOrderNo(orderNumber, OrderStatus.SUCCESS);
            //更新用户接口关系表
            Orders orders = orderService.getOrdersByOrderNumber(orderNumber);
            Integer number = orders.getNumber();
            Long interfaceInfoId = orders.getInterfaceInfoId();
            Long userId = orders.getUserId();
           UserInterfaceInfo interfaceInfoByUserIdAndInterfaceInfoId = userInterfaceInfoService.getInterfaceInfoByUserIdAndInterfaceInfoId(userId, interfaceInfoId);
           if(interfaceInfoByUserIdAndInterfaceInfoId==null){
               UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
               userInterfaceInfo.setInterfaceInfoId(interfaceInfoId);
               userInterfaceInfo.setUserId(userId);
               userInterfaceInfo.setLeftNum(number);
                userInterfaceInfoService.save(userInterfaceInfo);
           }else{
               Integer leftNum = interfaceInfoByUserIdAndInterfaceInfoId.getLeftNum();
               UpdateWrapper<UserInterfaceInfo> updateWrapper=new UpdateWrapper<>();
               updateWrapper.set("leftNum",leftNum+number);
               userInterfaceInfoService.update(updateWrapper);
           }


//            //并记录支付日志
//            paymentInfoService.createPaymentInfoForAliPay(alipayTradeQueryResponse);
        }
    }
    /**
     * 关单接口的调用
     * @param orderNumber 订单号
     */
    private void closeOrder(String orderNumber) {

        try {
            log.info("关单接口的调用，订单号 ===> {}", orderNumber);

            AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderNumber);
            request.setBizContent(bizContent.toString());
            AlipayTradeCloseResponse response = alipayClient.execute(request);

            if(response.isSuccess()){
                log.info("调用成功，返回结果 ===> " + response.getBody());
            } else {
                log.info("调用失败，返回码 ===> " + response.getCode() + ", 返回描述 ===> " + response.getMsg());
                //throw new RuntimeException("关单接口的调用失败");
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("关单接口的调用失败");
        }
    }
}




